#!/bin/sh
# Start/stop/restart sickrage.

# rc.sickrage created by Jeremy Brent Hansen for Slackware

# Set program name in case you want to run sick{beard|rage|gear|etc}
PROG=${PROG:-sickrage}

# Source SickRage configuration
if [ -f /etc/${PROG}.conf ]; then
        . /etc/${PROG}.conf
fi

# Ensure all required variables are set in conf file
# Edit conf file in /etc/sickrage.conf for any changes
for var in USERNAME HOMEDIR DATADIR PIDFILE PORT; do
  if [ -z "${!var}" ]; then
    echo "/etc/${PROG}.conf is missing some or all required variables ($var)."
    echo "Please check the file and try again."
    exit 1
  fi
done

# Check if the pid file exists
check() {
  if [ -e $PIDFILE ]; then
    STATUS=running
  else
    STATUS=stopped
  fi
}

status() {
  if [ $STATUS == "running" ]; then
    echo "${PROG} currently running or not shut down properly."
    echo "PIDfile: $PIDFILE already exists."
  elif [ $STATUS == "stopped" ]; then
    echo "${PROG} not started."
    echo "PIDfile: $PIDFILE does not exist."
  else
    echo "Status unknown."
  fi
}

start() {
  if [ $STATUS == "running" ]; then
    echo "$PROG already running or not shut down properly."
  else
    echo -n "Starting ${PROG}: "
    su $USERNAME -s /bin/sh -c "python ${HOMEDIR}/SickBeard.py --daemon --pidfile=${PIDFILE} --datadir=${DATADIR} --port=${PORT} &> /dev/null"
    if (( $? == 0 )); then
      echo "Startup Successful"
    else
      echo "Startup Failed. Please try running the following to see the errors."
      echo "su $USERNAME -s /bin/sh -c \"python ${HOMEDIR}/SickBeard.py --daemon --pidfile=${PIDFILE} --datadir=${DATADIR} --port=${PORT}\""
    fi
  fi
}

stop() {
  if [ $STATUS == "stopped" ]; then
    echo "${PROG} doesn't seem to be running. Please try running"
    echo "$0 start"
  else
    if [ "$EUID" -ne 0 ];then
      echo "Please run as root"
      exit 1
    fi
    PID=$(cat $PIDFILE)
    echo -n $"Shutting down ${PROG}: "
    curl -f http://localhost:${PORT}/home/shutdown/?pid=${PID} &> /dev/null
    if [ $? -gt 0 ]; then
      echo "Normal Shutdown Failed - Attempting to kill the process."
      echo $?
      sleep 7
      kill -9 $PID
    else
      echo "Shutdown Successful"
    fi
  fi
}

case "$1" in
  start)
        check
        start
        ;;
  stop)
        check
        stop
        ;;
  restart)
        check
        stop
        start
        ;;
  status)
        check
        status
        ;;
  *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
esac
